<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas" width=400 height=400></canvas>
</body>

</html>
<script>
  /** @type {HTMLCanvasElement} */
  let canvas = document.getElementById('canvas');
  let gl = canvas.getContext('webgl');
  gl.clearColor(0.1, 0.5, 0.4, 0.3);
  gl.clear(gl.COLOR_BUFFER_BIT);

  function initShader(gl, vertexSource, fragmentSource) {
    // 创造着色器对象
    let vertexShader = gl.createShader(gl.VERTEX_SHADER);
    let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(vertexShader, vertexSource);
    gl.shaderSource(fragmentShader, fragmentSource)
    gl.compileShader(vertexShader);
    gl.compileShader(fragmentShader);
    let program = gl.createProgram();
    gl.attachShader(program, vertexShader)
    gl.attachShader(program, fragmentShader)
    gl.linkProgram(program);
    gl.useProgram(program);
    return program
  }
  let vertexSource = `
    attribute vec4 position;
    void main(){
      float r = radians(30.0);
      float cos = cos(r);
      float sin = sin(r);
      // 绕x轴
      mat4 mx = mat4(1.0,0.0,0.0,0.0, 0.0,cos,sin,0.0, 0.0,-sin,cos,0.0, 0.0,0.0,0.0,1.0);
      // 绕y轴
      mat4 my = mat4(cos,0.0,-sin,0.0, 0.0,1.1,0.0,0.0, sin,0.0,cos,0.0, 0.0,0.0,0.0,1.0);
      // 绕z轴
      mat4 mz = mat4(cos,sin,0.0,0.0, -sin,cos,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0);
      gl_Position = mx*my*position;
    }
  `;
  let fragmentSource = `
    void main(){
      gl_FragColor = vec4(1.0,0.0,0.6,0.8);
    }
  `;
  let program = initShader(gl, vertexSource, fragmentSource);
  let positionIndex = gl.getAttribLocation(program, 'position');

  let data = new Float32Array([
    // z 0.5
    0.5, 0.5, 0.5,
    0.5, -0.5, 0.5,
    -0.5, -0.5, 0.5,
    -0.5, 0.5, 0.5,
    // z -0.5
    0.5, 0.5, -0.5,
    0.5, -0.5, -0.5,
    -0.5, -0.5, -0.5,
    -0.5, 0.5, -0.5
  ]);
  let buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER,buffer);
  gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
  gl.vertexAttribPointer(positionIndex,3,gl.FLOAT,false,0,0);
  gl.enableVertexAttribArray(positionIndex);

  // 创造一个索引数组
  
  let dataIndex = new Uint8Array([
    // 前四个点是一个矩形
    0,1,2,3,
    // 后四个点是一个矩形
    4,5,6,7,

    // 使用第一和第5个点 形成一条线
    0,4,
    1,5,
    2,6,
    3,7
  ])
  let indexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indexBuffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,dataIndex,gl.STATIC_DRAW);
  
  gl.drawElements(gl.LINE_LOOP,4,gl.UNSIGNED_BYTE,0)
  gl.drawElements(gl.LINE_LOOP,4,gl.UNSIGNED_BYTE,4)
  gl.drawElements(gl.LINES,8,gl.UNSIGNED_BYTE,8)



</script>